import { ChangeEvent, useEffect, useState } from 'react'
import { Space, Input, Button, message } from 'antd';
import styles from './login.module.scss'
//init.ts如果报错  去vite-env.d.ts里声明
import initLoginBg from './init.ts'
//覆盖ui组件的样式
import './login.less'
//引入验证码图片 
import { CaptchaAPI, LoginAPI } from "@/request/api"
import {useNavigate} from 'react-router-dom'
// import { useSubmit } from 'react-router-dom';
const View = () => {
    const navigateTo = useNavigate()
    //加载背景组件的时机是在生命周期的函数
    useEffect(() => {
        initLoginBg();
        window.onresize = function () {
            initLoginBg();
        };
        getCaptchaImg();
    }, [])

    //定义一个变量（变量是用户名）
    const [userNameValue, setuserNameValue] = useState("");
    //密码
    const [passwordValue, setpasswordValue] = useState("");
    //验证码
    const [captchaValue, setcaptchaValue] = useState("");

    const [captchaImg, setCaptchaImg] = useState("");


    //获取用户输入的信息
    //ChangeEvent 是一个泛型，你必须提供什么样的DOM元素正在被使用。HTMLInputElement 特指HTML的输入标签
    const userNameChange = (e: ChangeEvent<HTMLInputElement>) => {
        console.log(e.target.value);
        //通过usernameChange点击事件获取到的用户名这个变量并将其赋值给userNameValue --->  userNameValue = e.target.value
        setuserNameValue(e.target.value);
    }
    const passwordChange = (e: ChangeEvent<HTMLInputElement>) => {
        setpasswordValue(e.target.value);
    }
    const captchaChange = (e: ChangeEvent<HTMLInputElement>) => {
        setcaptchaValue(e.target.value);
    }
    //点击登录事件函数
    const toLogin = async () => {
        console.log("用户名，密码，验证码分别是", userNameValue, passwordValue, captchaValue);
        if (!userNameValue.trim() || !passwordValue.trim() || !captchaValue.trim()) {
            message.warning("请完整输入信息！")
            return
        }
        //发起登录请求
        let loginAPIRes = await LoginAPI({
            username: userNameValue,
            password: passwordValue,
            code: captchaValue,
            uuid: localStorage.getItem("uuid") as string
        })
        console.log(loginAPIRes);
        if (loginAPIRes.code === 200) {
            //1、提示登录成功
            message.success('登录成功！')
            //2、保存token
            localStorage.setItem('lege-management-token', loginAPIRes.token)
            //3、跳转到/page1
            navigateTo('/page1')
            //4、删除本地保存中的uuid
            localStorage.removeItem('uuid')
        }
    }

    //获取验证码函数
    const getCaptchaImg = async () => {
        // CaptchaAPI().then((res) =>{
        //     console.log(res);
        // })
        let captchaAPIRes = await CaptchaAPI();
        console.log(captchaAPIRes);
        if (captchaAPIRes.code === 200) {
            setCaptchaImg('data:image/gif;base64,' + captchaAPIRes.img)
            localStorage.setItem("uuid", captchaAPIRes.uuid)
        }
    }

    return (
        <div className={styles.loginPage}>
            <canvas id='canvas' style={{ display: "block" }}></canvas>
            <div className={styles.loginBox + ' loginbox'}>
                <div className={styles.title}>
                    <h1>前端&nbsp;&nbsp;通用后台系统</h1>
                    <p> strive everyday </p>
                </div>
                <div className='form'>
                    <Space direction="vertical" size="large" style={{ display: 'flex' }}>
                        <Input placeholder='用户名' onChange={userNameChange} />
                        <Input.Password placeholder='密码' onChange={passwordChange} />
                        <div className='captchaBox'>
                            <Input placeholder='验证码' onChange={captchaChange} />
                            <div className='captchaImg' onClick={getCaptchaImg}>
                                <img height="38" src={captchaImg} alt="" />
                            </div>
                        </div>
                        <Button type='primary' className='loginButton' block onClick={toLogin}>登录</Button>
                    </Space>
                </div>
            </div>
        </div>
    )
}

export default View